package com.atguigu.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mchange.v2.c3p0.DataSources;
import com.mysql.cj.jdbc.AbandonedConnectionCleanupThread;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;

/**
 * get connection
 * and
 * close connection
 * test commit
 * @author dl
 * @create 2020-04-18-9:57
 */
public class JDBCUtils {
	private static Map<Long,Connection> map = new ConcurrentHashMap<>();

	private static DataSource ds = new ComboPooledDataSource("bookStoreConfig");

	/**
	 * getConnection
	 * @return
	 */
	public static Connection getConnection() {
		long id = Thread.currentThread().getId();
		Connection connection = map.get(id);
		if (connection == null) {
			try {
				connection = ds.getConnection();
				map.put(id,connection);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return connection;
	}

	/**
	 * releaseConnection
	 * @param
	 */
	public static void releaseConnection() {
		Connection connection = getConnection();
		try {
			if (connection != null)
				connection.close();
				map.remove(Thread.currentThread().getId());
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/** 销毁数据库连接池 TODO 需要看看这个为什么是这样处理的 */
	public static void destroy() {
		/** 清理DriverManager中的注册信息 */
		Enumeration<Driver> drivers = DriverManager.getDrivers();
		while (drivers.hasMoreElements()) {
			Driver driver = drivers.nextElement();
			try {
				DriverManager.deregisterDriver(driver);
			} catch (SQLException e) {
				System.out.println("取消失败");
			}

		}
		try {
			/** 销毁数据库连接池 */
			DataSources.destroy(ds);
		} catch (SQLException throwables) {
			throwables.printStackTrace();
		}
		/** 中止之后的线程 */
		try {
			AbandonedConnectionCleanupThread.checkedShutdown();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
